﻿using NetTopologySuite.Geometries;

namespace RemoteSensingImageDirectServer.Untils.Pool
{
    public class MatStretchPool
    {
        /// <summary>
        /// 私有静态锁对象，减少锁的范围
        /// </summary>
        private static readonly object syncRoot = new();

        /// <summary>
        /// 私有静态变量引用自身实例
        /// </summary>
        private static volatile MatStretchPool? instance = null;

        /// <summary>
        /// 公有静态方法，提供一个全局访问点
        /// </summary>
        /// <returns></returns>
        public static MatStretchPool Instance()
        {
            // 当instance为null时，才进行加锁处理
            if (instance == null)
            {
                // 双重检查锁定，提高性能
                lock (syncRoot)
                {
                    instance ??= new MatStretchPool();
                }
            }
            return instance;
        }

        #region LUT映射
        /// <summary>
        /// LUT映射表
        /// </summary>
        private static readonly Dictionary<double, byte[]> LutCache = new Dictionary<double, byte[]>();

        public byte[] GetLut(double val)
        {
            lock (syncRoot)
            {
                if (LutCache.TryGetValue(val, out var lut))
                {
                    return lut;
                }
                else
                {
                    lut = new byte[256];

                    for (int i = 0; i < 256; i++)
                    {
                        lut[i] = (byte)(Math.Pow((float)(i / 255.0), val) * 255.0f);
                    }

                    LutCache.TryAdd(val, lut);

                    return lut;
                }
            }
        }
        #endregion
    }
}
